<template>
  <view class="files-page">
    <!-- 筛选标签 -->
    <view class="filter-tabs">
      <view 
        v-for="(tab, index) in filterTabs" 
        :key="index"
        :class="['tab-item', { active: currentTab === tab.value }]"
        @click="switchTab(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>
    
    <!-- 文件列表 -->
    <view class="files-list">
      <view 
        v-for="(file, index) in fileList" 
        :key="index"
        class="file-item"
        @click="viewFile(file)"
      >
        <view class="file-icon">
          <u-icon :name="getFileIcon(file.type)" size="32" color="#4a6bef"></u-icon>
        </view>
        
        <view class="file-info">
          <view class="file-name">{{ file.name }}</view>
          <view class="file-details">
            <text>{{ formatFileSize(file.size) }}</text>
            <text class="file-time">{{ formatTime(file.uploadTime) }}</text>
          </view>
          <view class="file-status" :class="file.status">
            {{ getStatusText(file.status) }}
          </view>
        </view>
        
        <view class="file-actions">
          <view class="action-btn print" @click.stop="printFile(file)" v-if="file.status === 'processed'">
            <u-icon name="printer" size="16" color="#ffffff"></u-icon>
          </view>
          <view class="action-btn delete" @click.stop="deleteFile(file)">
            <u-icon name="trash" size="16" color="#ffffff"></u-icon>
          </view>
        </view>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="fileList.length === 0 && !isLoading">
        <image src="/static/icons/empty.png" class="empty-icon" />
        <view class="empty-text">暂无文件</view>
        <view class="empty-tip">点击右上角"+"上传文件</view>
        <view class="empty-action">
          <button class="upload-now-btn" @click="uploadFile">立即上传</button>
        </view>
      </view>
      
      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore && fileList.length > 0">
        <view v-if="isLoadingMore" class="loading-text">
          <u-loading-icon mode="circle" size="24" color="#909399"></u-loading-icon>
          <text>加载中...</text>
        </view>
        <view v-else class="load-more-btn" @click="loadMore">加载更多</view>
      </view>
    </view>
    
    <!-- 底部操作栏 -->
    <view class="bottom-bar" v-if="fileList.length > 0">
      <button class="bottom-btn" @click="uploadFile">
        <u-icon name="plus" size="18" color="#ffffff" style="margin-right: 8rpx;"></u-icon>
        上传文件
      </button>
    </view>
  </view>
</template>

<script>
import { getFileList, deleteFile } from '../../api/files.js'

export default {
  name: 'FilesListPage',
  
  data() {
    return {
      currentTab: 'all',
      filterTabs: [
        { label: '全部', value: 'all' },
        { label: '文档', value: 'document' },
        { label: '图片', value: 'image' },
        { label: '其他', value: 'other' }
      ],
      fileList: [],
      currentPage: 1,
      pageSize: 20,
      hasMore: true,
      isLoading: false,
      isLoadingMore: false
    }
  },
  
  onLoad() {
    this.initStatusBar()
    this.loadFileList()
  },
  
  onShow() {
    this.refreshData()
  },
  
  onReachBottom() {
    if (this.hasMore && !this.isLoadingMore) {
      this.loadMore()
    }
  },
  
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    /**
     * 初始化状态栏高度
     */
    initStatusBar() {
      const systemInfo = uni.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0
      
      if (typeof document !== 'undefined' && document.documentElement) {
        document.documentElement.style.setProperty('--status-bar-height', statusBarHeight * 2 + 'rpx')
      }
    },
    
    /**
     * 返回上一页
     */
    goBack() {
      uni.navigateBack()
    },
    
    /**
     * 上传文件
     */
    uploadFile() {
      uni.navigateTo({
        url: '/pages/files/upload'
      })
    },
    
    /**
     * 切换标签
     */
    switchTab(tab) {
      if (this.currentTab === tab) return
      
      this.currentTab = tab
      this.refreshData()
    },
    
    /**
     * 刷新数据
     */
    async refreshData() {
      this.currentPage = 1
      this.fileList = []
      this.hasMore = true
      await this.loadFileList()
    },
    
    /**
     * 加载文件列表
     */
    async loadFileList() {
      if (this.isLoading) return
      
      this.isLoading = true
      
      try {
        const params = {
          page: this.currentPage,
          limit: this.pageSize,
          type: this.currentTab !== 'all' ? this.currentTab : undefined
        }
        
        const result = await getFileList(params)
        
        if (result.success) {
          const data = result.data
          
          if (this.currentPage === 1) {
            this.fileList = data.files
          } else {
            this.fileList.push(...data.files)
          }
          
          this.hasMore = this.currentPage < data.totalPages
        } else {
          this.showError(result.message || '加载文件列表失败')
        }
      } catch (error) {
        console.error('加载文件列表失败:', error)
        this.showError('加载文件列表失败')
      } finally {
        this.isLoading = false
      }
    },
    
    /**
     * 加载更多
     */
    async loadMore() {
      if (!this.hasMore || this.isLoadingMore) return
      
      this.isLoadingMore = true
      this.currentPage++
      
      try {
        await this.loadFileList()
      } finally {
        this.isLoadingMore = false
      }
    },
    
    /**
     * 查看文件
     */
    viewFile(file) {
      uni.navigateTo({
        url: `/pages/files/detail?id=${file.id}`
      })
    },
    
    /**
     * 打印文件
     */
    printFile(file) {
      uni.navigateTo({
        url: `/pages/print/setup?fileId=${file.id}`
      })
    },
    
    /**
     * 删除文件
     */
    deleteFile(file) {
      uni.showModal({
        title: '确认删除',
        content: `确定要删除文件"${file.name}"吗？`,
        confirmColor: '#f56c6c',
        success: async (res) => {
          if (res.confirm) {
            try {
              uni.showLoading({
                title: '删除中...',
                mask: true
              })
              
              const result = await deleteFile(file.id)
              
              if (result.success) {
                this.showSuccess('删除成功')
                this.refreshData()
              } else {
                this.showError(result.message || '删除失败')
              }
            } catch (error) {
              console.error('删除文件失败:', error)
              this.showError('删除失败')
            } finally {
              uni.hideLoading()
            }
          }
        }
      })
    },
    
    /**
     * 获取文件图标
     */
    getFileIcon(type) {
      const iconMap = {
        'pdf': 'file-pdf',
        'doc': 'file-word',
        'docx': 'file-word',
        'xls': 'file-excel',
        'xlsx': 'file-excel',
        'ppt': 'file-ppt',
        'pptx': 'file-ppt',
        'txt': 'file-text',
        'jpg': 'image',
        'jpeg': 'image',
        'png': 'image',
        'gif': 'image'
      }
      return iconMap[type.toLowerCase()] || 'file'
    },
    
    /**
     * 格式化文件大小
     */
    formatFileSize(size) {
      if (size < 1024) {
        return size + 'B'
      } else if (size < 1024 * 1024) {
        return (size / 1024).toFixed(1) + 'KB'
      } else {
        return (size / (1024 * 1024)).toFixed(1) + 'MB'
      }
    },
    
    /**
     * 格式化时间
     */
    formatTime(timestamp) {
      const date = new Date(timestamp)
      const now = new Date()
      const diff = now - date
      
      if (diff < 60000) {
        return '刚刚'
      } else if (diff < 3600000) {
        return Math.floor(diff / 60000) + '分钟前'
      } else if (diff < 86400000) {
        return Math.floor(diff / 3600000) + '小时前'
      } else if (diff < 604800000) { // 7天内
        return Math.floor(diff / 86400000) + '天前'
      } else {
        return date.toLocaleDateString()
      }
    },
    
    /**
     * 获取状态文本
     */
    getStatusText(status) {
      const statusMap = {
        'uploading': '上传中',
        'processing': '处理中',
        'processed': '已处理',
        'failed': '处理失败'
      }
      return statusMap[status] || '未知'
    },
    
    /**
     * 显示成功提示
     */
    showSuccess(message) {
      uni.showToast({
        title: message,
        icon: 'success',
        duration: 2000
      })
    },
    
    /**
     * 显示错误提示
     */
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.files-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;
}

// 导航栏样式
.nav-bar {
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 32rpx;
  padding-top: var(--status-bar-height);
  background: linear-gradient(135deg, #4a6bef, #7a5af8);
  position: relative;
  z-index: 100;
  box-sizing: content-box;
}

.nav-left, .nav-right {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:active {
    opacity: 0.7;
    transform: scale(0.95);
  }
}

.back-icon, .upload-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60rpx;
  height: 60rpx;
}

.nav-title {
  flex: 1;
  text-align: center;
  font-size: 34rpx;
  font-weight: bold;
  color: white;
}

// 筛选标签
.filter-tabs {
  display: flex;
  background: white;
  padding: 20rpx;
  margin: 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 16rpx 0;
  font-size: 28rpx;
  color: #606266;
  border-radius: 12rpx;
  position: relative;
  transition: all 0.3s ease;
  
  &.active {
    color: #4a6bef;
    font-weight: 500;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 40rpx;
      height: 6rpx;
      background: #4a6bef;
      border-radius: 3rpx;
    }
  }
  
  &:active {
    opacity: 0.7;
  }
}

// 文件列表
.files-list {
  padding: 20rpx;
}

.file-item {
  display: flex;
  align-items: center;
  background: white;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  
  &:active {
    transform: scale(0.98);
    background: #f9f9f9;
  }
}

.file-icon {
  margin-right: 24rpx;
  width: 80rpx;
  height: 80rpx;
  background: #f0f5ff;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.file-info {
  flex: 1;
  overflow: hidden;
}

.file-name {
  font-size: 30rpx;
  color: #303133;
  font-weight: 500;
  margin-bottom: 12rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-details {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  color: #909399;
  margin-bottom: 12rpx;
}

.file-time {
  margin-left: 16rpx;
  position: relative;
  padding-left: 16rpx;
  
  &::before {
    content: '';
    position: absolute;
    left: 6rpx;
    top: 50%;
    transform: translateY(-50%);
    width: 4rpx;
    height: 4rpx;
    border-radius: 50%;
    background: #c0c4cc;
  }
}

.file-status {
  font-size: 22rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  display: inline-block;
  
  &.uploading {
    background: #e6f7ff;
    color: #1890ff;
  }
  
  &.processing {
    background: #fff7e6;
    color: #fa8c16;
  }
  
  &.processed {
    background: #f6ffed;
    color: #52c41a;
  }
  
  &.failed {
    background: #fff2f0;
    color: #ff4d4f;
  }
}

.file-actions {
  display: flex;
  gap: 16rpx;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  
  &.print {
    background: #4a6bef;
    
    &:active {
      background: #3a5bd0;
    }
  }
  
  &.delete {
    background: #f56c6c;
    
    &:active {
      background: #e45656;
    }
  }
}

// 空状态
.empty-state {
  text-align: center;
  padding: 120rpx 40rpx;
  color: #909399;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
  opacity: 0.6;
}

.empty-text {
  font-size: 34rpx;
  margin-bottom: 16rpx;
  color: #606266;
}

.empty-tip {
  font-size: 28rpx;
  color: #909399;
  margin-bottom: 40rpx;
}

.empty-action {
  .upload-now-btn {
    display: inline-block;
    background: #4a6bef;
    color: white;
    font-size: 30rpx;
    padding: 16rpx 40rpx;
    border-radius: 40rpx;
    border: none;
    
    &:active {
      opacity: 0.9;
      transform: scale(0.98);
    }
  }
}

// 加载更多
.load-more {
  text-align: center;
  padding: 40rpx 0;
}

.loading-text, .load-more-btn {
  font-size: 28rpx;
  color: #909399;
  padding: 16rpx 32rpx;
  border-radius: 40rpx;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 12rpx;
}

.load-more-btn {
  background: #f0f2f5;
  transition: all 0.3s ease;
  
  &:active {
    background: #e9ecef;
    transform: scale(0.98);
  }
}

// 底部操作栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx;
  background: white;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.bottom-btn {
  width: 100%;
  height: 88rpx;
  border-radius: 44rpx;
  background: #4a6bef;
  color: white;
  font-size: 32rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  
  &:active {
    opacity: 0.9;
    transform: scale(0.98);
  }
}
</style>